import React, { useState, useEffect, useRef, Component } from 'react';
import type { ErrorInfo } from 'react';
import { 
    Button, 
    Spin, 
    Card, 
    Alert, 
    Typography, 
    Space, 
    Divider, 
    Switch, 
    Select, 
    notification,
    message
} from 'antd';
import { 
    ReadOutlined, 
    SmileOutlined, 
    CloseOutlined, 
    CheckCircleOutlined, 
    WarningOutlined, 
    BulbOutlined, 
    RobotOutlined, 
    UserOutlined, 
    ThunderboltOutlined,
    FullscreenOutlined
} from '@ant-design/icons';
import { KNOWLEDGE_LIB_ROUTER } from "~src/constants"
import ReactMarkdown from 'react-markdown';

// 注意：已经有 MarkdownErrorBoundary 组件，不需要重复定义

// 错误边界组件，防止 ReactMarkdown 渲染错误导致整个面板消失
class MarkdownErrorBoundary extends Component<{children: React.ReactNode, fallback?: React.ReactNode}, {hasError: boolean}> {
    constructor(props: {children: React.ReactNode, fallback?: React.ReactNode}) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(_: Error) {
        return { hasError: true };
    }

    componentDidCatch(error: Error, errorInfo: ErrorInfo) {
        console.error('MarkdownErrorBoundary 捕获到错误 - caught an error:', error);
        console.error('错误详情 - Error details:', errorInfo);
        
        // 在错误发生时主动调用 onKeepVisible 保持面板可见
        // 这是一个关键点，确保即使渲染出错也不会导致面板消失
        const getUrlPanel = document.getElementById('ai-side-panel');
        if (getUrlPanel && getUrlPanel.dataset && getUrlPanel.dataset.keepVisibleFn) {
            try {
                const keepVisibleFn = new Function('return ' + getUrlPanel.dataset.keepVisibleFn)();
                if (typeof keepVisibleFn === 'function') {
                    console.log('错误边界主动调用保持面板可见 - Error boundary actively keeping panel visible');
                    keepVisibleFn();
                }
            } catch (e) {
                console.error('尝试保持面板可见时出错 - Error trying to keep panel visible:', e);
            }
        }
    }

    render() {
        if (this.state.hasError) {
            // 当发生错误时，显示备用内容
            return this.props.fallback || <div className="markdown-error">内容渲染失败，请尝试刷新。</div>;
        }

        return this.props.children;
    }
}

// 简单的 Markdown 解析函数
const parseMarkdownToJSX = (text: string) => {
    console.log('parseMarkdownToJSX called with:', text);
    
    if (!text || typeof text !== 'string') {
        console.log('No text or not string, returning 无内容');
        return <div style={{ padding: '10px', color: '#999' }}>无内容</div>;
    }
    
    if (!text.trim()) {
        console.log('Empty text after trim');
        return <div style={{ padding: '10px', color: '#999' }}>内容为空</div>;
    }

    const lines = text.split('\n');
    const elements: React.ReactNode[] = [];
    let listItems: string[] = [];
    
    const flushListItems = () => {
        if (listItems.length > 0) {
            elements.push(
                <ul key={`list-${elements.length}`} style={{ marginLeft: '20px', marginBottom: '16px' }}>
                    {listItems.map((item, index) => (
                        <li key={index} style={{ marginBottom: '4px' }}>{parseInlineMarkdown(item)}</li>
                    ))}
                </ul>
            );
            listItems = [];
        }
    };

    const parseInlineMarkdown = (line: string) => {
        // 处理行内样式
        const parts = [];
        let currentIndex = 0;
        
        // 粗体 **text**
        line = line.replace(/\*\*(.*?)\*\*/g, (match, content) => {
            return `<strong>${content}</strong>`;
        });
        
        // 斜体 *text* (避免与粗体冲突)
        line = line.replace(/\*([^*]+)\*/g, (match, content) => {
            // 确保不是粗体的一部分
            if (!match.includes('**')) {
                return `<em>${content}</em>`;
            }
            return match;
        });
        
        // 代码 `code`
        line = line.replace(/`([^`]+)`/g, (match, content) => {
            return `<code style="background-color: #f5f5f5; padding: 2px 4px; border-radius: 3px; font-family: monospace;">${content}</code>`;
        });
        
        return <span dangerouslySetInnerHTML={{ __html: line }} />;
    };

    lines.forEach((line, index) => {
        line = line.trim();
        
        if (line === '') {
            flushListItems();
            elements.push(<br key={`br-${index}`} />);
            return;
        }
        
        // 标题
        if (line.startsWith('### ')) {
            flushListItems();
            elements.push(
                <h3 key={index} style={{ fontSize: '18px', fontWeight: 'bold', margin: '16px 0 8px 0', color: '#333' }}>
                    {parseInlineMarkdown(line.substring(4))}
                </h3>
            );
        } else if (line.startsWith('## ')) {
            flushListItems();
            elements.push(
                <h2 key={index} style={{ fontSize: '20px', fontWeight: 'bold', margin: '20px 0 10px 0', color: '#333' }}>
                    {parseInlineMarkdown(line.substring(3))}
                </h2>
            );
        } else if (line.startsWith('# ')) {
            flushListItems();
            elements.push(
                <h1 key={index} style={{ fontSize: '24px', fontWeight: 'bold', margin: '24px 0 12px 0', color: '#333' }}>
                    {parseInlineMarkdown(line.substring(2))}
                </h1>
            );
        } else if (line.startsWith('- ') || line.startsWith('* ')) {
            // 列表项
            listItems.push(line.substring(2));
        } else {
            // 普通段落
            flushListItems();
            elements.push(
                <p key={index} style={{ margin: '8px 0', lineHeight: '1.6' }}>
                    {parseInlineMarkdown(line)}
                </p>
            );
        }
    });
    
    flushListItems(); // 处理最后的列表项
    
    return <div>{elements}</div>;
};

export namespace GetUrlPanel {
    export enum Action {
        GetUrl = 'GetUrl',
        GetUrlStart = 'GetUrlStart',
        GetUrlResolve = 'GetUrlResolve',
        GetUrlReject = 'GetUrlReject',
        ShowPanel = 'ShowPanel',
        ClosePanel = 'ClosePanel'
    }

    export type Message = {
        id: string
        action: Action
        data?: any
    }
}

// Styles for the side panel
const styles = {
    sidePanel: {
        position: 'fixed',
        top: 0,
        right: 0,
        width: '420px',
        height: '100vh',
        backgroundColor: '#fff',
        boxShadow: '-2px 0 10px rgba(0, 0, 0, 0.1)',
        zIndex: 999999,
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
        transition: 'transform 0.3s ease',
        borderLeft: '1px solid #e8e8e8'
    },
    header: {
        padding: '16px',
        borderBottom: '1px solid #e8e8e8',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        background: 'linear-gradient(135deg, #1677ff 0%, #4096ff 100%)'
    },
    headerTitle: {
        color: '#fff',
        margin: 0
    },
    closeButton: {
        background: 'transparent',
        border: 'none',
        cursor: 'pointer',
        color: '#fff'
    },
    content: {
        padding: '16px',
        overflowY: 'auto',
        flex: 1
    },
    successIcon: {
        fontSize: '48px',
        color: '#52c41a',
        marginBottom: '16px'
    },
    errorIcon: {
        fontSize: '48px',
        color: '#ff4d4f',
        marginBottom: '16px'
    },
    loadingContainer: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '20px'
    },
    loadingText: {
        marginTop: '16px',
        color: '#1677ff'
    }
};

const { Title, Text } = Typography;
const { Option } = Select;

interface MindModel {
    value: string | null;
    text: string;
    isDefault: boolean | null;
}

interface GetUrlPanelProps {
    visible: boolean;
    onClose: () => void;
    status: 'loading' | 'success' | 'error';
    errorMessage?: string;
    infoGuid?: string;
    onKeepVisible?: () => void;
}

/**
 * GetUrlPanel React Component
 */
export const GetUrlPanelComponent: React.FC<GetUrlPanelProps> = ({
    visible,
    onClose,
    status,
    errorMessage,
    infoGuid,
    onKeepVisible
}) => {
    const [isPersonalMode, setIsPersonalMode] = useState(true);
    const [userMindModels, setUserMindModels] = useState<MindModel[]>([]);
    const [systemMindModels, setSystemMindModels] = useState<MindModel[]>([]);
    const [selectedModel, setSelectedModel] = useState<string>('');
    const [loading, setLoading] = useState(false);
    const [generating, setGenerating] = useState(false);
    const [generatedContent, setGeneratedContent] = useState<string>('');
    const [collectSuccess, setCollectSuccess] = useState(false);
    const [currentInfoGuid, setCurrentInfoGuid] = useState<string>('');

    const [showFullscreen, setShowFullscreen] = useState(false);
    const [showSuccessAlert, setShowSuccessAlert] = useState(true);
    const [showCategoryCard, setShowCategoryCard] = useState(true);
    const [isExpanded, setIsExpanded] = useState(false);
    
    // Category selection state
    const [selectedCategory, setSelectedCategory] = useState<string>('');
    const [associatingCategory, setAssociatingCategory] = useState(false);
    const [searchTerm, setSearchTerm] = useState<string>('');
    const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
    const [categories, setCategories] = useState<Array<{value: string, label: string}>>([]);
    const [loadingCategories, setLoadingCategories] = useState(false);
    
    // Mock category data - will be replaced with API call later
    const mockCategories = [
        { value: 'tech', label: '🔧 Technology & Development' },
        { value: 'business', label: '💼 Business & Finance' },
        { value: 'research', label: '📚 Research & Education' },
        { value: 'design', label: '🎨 Design & Creative' },
        { value: 'health', label: '🏥 Health & Wellness' },
        { value: 'news', label: '📰 News & Current Events' },
        { value: 'entertainment', label: '🎬 Entertainment' },
        { value: 'travel', label: '✈️ Travel & Lifestyle' },
        { value: 'science', label: '🔬 Science & Innovation' },
        { value: 'other', label: '📂 Other' }
    ];
    
    // Load categories from background via message
    const loadCategories = async () => {
        console.log('🚀 loadCategories函数被调用 - loadCategories function called');
        console.log('开始加载分类数据 - Starting to load categories');
        setLoadingCategories(true);
        
        try {
            // 发送消息到background请求分类数据
            console.log('发送GET_CATEGORIES消息到background - Sending GET_CATEGORIES message to background');
            
            const response = await chrome.runtime.sendMessage({
                type: 'GET_CATEGORIES'
            });
            
            console.log('分类数据响应 - Categories response:', response);
            
            if (response && response.success && Array.isArray(response.data)) {
                console.log('分类数据加载成功 - Categories loaded successfully:', {
                    dataLength: response.data.length,
                    fromCache: response.fromCache
                });
                
                setCategories(response.data);
                
                // 如果有分类数据且当前没有选中任何分类，可以选择第一个作为默认值
                if (response.data.length > 0 && !selectedCategory) {
                    // 不自动选择，让用户手动选择
                    console.log('分类数据加载成功，共', response.data.length, '个分类');
                }
            } else {
                console.error('分类数据响应格式错误 - Invalid categories response format:', response);
                notification.warning({
                    message: 'Load Categories Failed',
                    description: response?.message || 'Failed to load categories from server.',
                    placement: 'topRight'
                });
                
                // 使用mock数据作为fallback
                console.log('使用mock数据作为备选 - Using mock data as fallback');
                setCategories(mockCategories);
            }
        } catch (error) {
            console.error('加载分类数据异常 - Exception loading categories:', error);
            notification.error({
                message: 'Load Categories Error',
                description: 'An error occurred while loading categories. Using default categories.',
                placement: 'topRight'
            });
            
            // 使用mock数据作为fallback
            setCategories(mockCategories);
        } finally {
            setLoadingCategories(false);
        }
    };
    
    // Filter categories based on search term (使用API数据而不是mock数据)
    const filteredCategories = categories.filter(category =>
        category.label.toLowerCase().includes(searchTerm.toLowerCase())
    );
    
    // Get selected category label for display (使用API数据而不是mock数据)
    const selectedCategoryLabel = categories.find(cat => cat.value === selectedCategory)?.label || '';
    
    // Handle category association
    const handleCategoryAssociation = async () => {
        if (!selectedCategory) {
            notification.warning({
                message: 'No Category Selected',
                description: 'Please select a category before associating the page.',
                placement: 'topRight'
            });
            return;
        }
        
        setAssociatingCategory(true);
        
        try {
            // 获取 infoGuid
            const currentInfoGuid = infoGuid || (await chrome.storage.local.get('lastInfoGuid')).lastInfoGuid;
            
            if (!currentInfoGuid) {
                notification.error({
                    message: 'Association Failed',
                    description: 'No content ID found. Please collect the page first.',
                    placement: 'topRight'
                });
                return;
            }
            
            console.log('发送RELATE_TAG消息到background - Sending RELATE_TAG message to background');
            console.log('参数 - Parameters:', {
                infoGuid: currentInfoGuid,
                tagName: selectedCategory
            });
            
            // 发送消息到background请求关联标签
            const response = await chrome.runtime.sendMessage({
                type: 'RELATE_TAG',
                params: {
                    infoGuid: currentInfoGuid,
                    tagName: selectedCategory
                }
            });
            
            console.log('关联标签响应 - Relate tag response:', response);
            
            if (response && response.success) {
                const categoryLabel = categories.find(cat => cat.value === selectedCategory)?.label || selectedCategory;
                
                notification.success({
                    message: 'Category Associated Successfully',
                    description: `This page has been associated with ${categoryLabel}`,
                    placement: 'topRight'
                });
                
                console.log('Page associated with category successfully:', selectedCategory);
            } else {
                console.error('关联标签失败 - Failed to relate tag:', response?.message);
                notification.error({
                    message: 'Association Failed',
                    description: response?.message || 'Failed to associate page with the selected category. Please try again.',
                    placement: 'topRight'
                });
            }
        } catch (error) {
            console.error('关联分类异常 - Exception associating category:', error);
            notification.error({
                message: 'Association Error',
                description: 'An error occurred while associating the category. Please try again.',
                placement: 'topRight'
            });
        } finally {
            setAssociatingCategory(false);
        }
    };
    
    // Load user mind models
    const loadUserMindModels = async (infoGuid: string) => {
        console.log('函数已调用: loadUserMindModels - Function called: loadUserMindModels');
        console.log('传入的infoGuid - Passed infoGuid:', infoGuid);
        
        try {
            setLoading(true);
            
            // 从chrome.storage中获取思维模型数据
            console.log('从chrome.storage获取思维模型数据 - Getting mind models from chrome.storage');
            const result = await chrome.storage.local.get('userMindModels');
            console.log('原始结果数据 - Raw result data:', result);
            
            // 处理可能的数据结构差异
            let models = [];
            if (result && result.userMindModels) {
                if (Array.isArray(result.userMindModels)) {
                    models = result.userMindModels;
                    console.log('结果数据是数组 - Result data is array, length:', models.length);
                } else if (typeof result.userMindModels === 'object') {
                    // 如果是对象但包含数组
                    const keys = Object.keys(result.userMindModels);
                    console.log('结果数据是对象 - Result data is object with keys:', keys);
                    
                    // 尝试不同的方式提取数组
                    if (Array.isArray(result.userMindModels[0])) {
                        models = result.userMindModels[0];
                        console.log('从对象[0]提取数组 - Extracted array from object[0], length:', models.length);
                    } else {
                        // 尝试将对象值转为数组
                        const values = Object.values(result.userMindModels);
                        if (values.length > 0) {
                            if (Array.isArray(values[0])) {
                                models = values[0];
                                console.log('从对象值提取数组 - Extracted array from object values[0], length:', models.length);
                            } else if (Array.isArray(values)) {
                                models = values;
                                console.log('使用对象值作为数组 - Using object values as array, length:', models.length);
                            }
                        }
                    }
                }
            }
            
            console.log('最终解析的思维模型数据 - Final parsed mind models data:', models);
            
            if (models && Array.isArray(models) && models.length > 0) {
                setUserMindModels(models);
                setSelectedModel(models[0]?.value || '');
                console.log('思维模型数据设置成功 - Mind models data set successfully');
            } else {
                console.log('在storage中未找到思维模型数据 - No mind model data found in storage');
            }
        } catch (error) {
            console.error('加载用户思维模型异常 - Exception loading user mind models:', error);
            message.error('Failed to load user mind models');
        } finally {
            setLoading(false);
        }
    };

    // Load system mind models
    const loadSystemMindModels = async () => {
        try {
            setLoading(true);
            console.log('开始加载系统思维模型 - Starting to load system mind models');
            
            // 使用 chrome.runtime.sendMessage 代替直接 API 调用
            console.log('发送消息到 background 脚本 - Sending message to background script');
            const response = await chrome.runtime.sendMessage({ type: 'GET_SYSTEM_MIND_MODELS' });
            console.log('收到 background 响应 - Received background response:', response);
            
            if (response && response.success) {
                console.log('系统思维模型加载成功 - System mind models loaded successfully:', response.data);
                
                // 确保数据是数组
                const models = Array.isArray(response.data) ? response.data : [];
                setSystemMindModels(models);
                
                // 设置默认选择
                const defaultModel = models.find((model: MindModel) => model.isDefault);
                if (defaultModel && defaultModel.value) {
                    setSelectedModel(defaultModel.value);
                } else if (models.length > 0 && models[0].value) {
                    setSelectedModel(models[0].value);
                }
            } else {
                console.error('加载系统思维模型失败 - Failed to load system mind models:', response?.message || 'Unknown error');
                message.error(response?.message || 'Failed to load system mind models');
                
                // 尝试从本地缓存加载
                try {
                    console.log('尝试从本地缓存加载系统思维模型 - Trying to load system mind models from local cache');
                    const cache = await chrome.storage.local.get('systemMindModels');
                    if (cache.systemMindModels && Array.isArray(cache.systemMindModels) && cache.systemMindModels.length > 0) {
                        console.log('从缓存加载系统思维模型成功 - Successfully loaded system mind models from cache');
                        setSystemMindModels(cache.systemMindModels);
                        if (cache.systemMindModels[0].value) {
                            setSelectedModel(cache.systemMindModels[0].value);
                        }
                    }
                } catch (cacheError) {
                    console.error('从缓存加载系统思维模型失败 - Failed to load system mind models from cache:', cacheError);
                }
            }
        } catch (error) {
            console.error('加载系统思维模型异常 - Exception loading system mind models:', error);
            message.error('Failed to load system mind models');
        } finally {
            setLoading(false);
        }
    };

    // 不再使用定时器来保持面板可见
    // 而是在组件挂载时调用一次 onKeepVisible
    useEffect(() => {
        if (onKeepVisible) {
            // 只在组件挂载时调用一次
            console.log('面板初始化 - Panel initialized');
            onKeepVisible();
        }
    }, [onKeepVisible]);
    
    // 在生成内容后再次确保面板可见
    useEffect(() => {
        if (generatedContent && onKeepVisible) {
            // 内容生成后再次确保面板可见
            console.log('内容生成后确保面板可见 - Ensuring panel visibility after content generation');
            onKeepVisible();
            
            // 再次调用，确保在异步渲染后仍然可见
            setTimeout(() => {
                if (onKeepVisible) {
                    console.log('延迟保持面板可见 - Delayed keeping panel visible');
                    onKeepVisible();
                }
            }, 100);
        }
    }, [generatedContent, onKeepVisible]);
    
    // Generate AI content
    const generateAIContent = async () => {
        if (!selectedModel) {
            message.warning('Please select a mind model first');
            return;
        }

        try {
            setGenerating(true);
            // 隐藏Success Alert和Page Category card
            setShowSuccessAlert(false);
            setShowCategoryCard(false);
            console.log('开始生成 AI 内容 - Starting to generate AI content');
            
            // 获取 infoGuid
            const currentInfoGuid = infoGuid || (await chrome.storage.local.get('lastInfoGuid')).lastInfoGuid;
            
            if (!currentInfoGuid) {
                message.error('No content ID found');
                setGenerating(false);
                return;
            }
            
            console.log('发送消息到 background 脚本 - Sending message to background script');
            console.log('参数 - Parameters:', {
                infoGuid: currentInfoGuid,
                mindPromptGuids: [selectedModel]
            });
            
            // 使用 chrome.runtime.sendMessage 代替直接 API 调用
            const response = await chrome.runtime.sendMessage({
                type: 'GENERATE_AI_CONTENT',
                params: {
                    infoGuid: currentInfoGuid,
                    mindPromptGuids: [selectedModel]
                }
            });
            
            console.log('收到 background 响应 - Received background response:', response);
            
            if (response && response.success) {
                console.log('AI 内容生成成功 - AI content generated successfully');
                
                // 输出原始数据类型和值
                console.log("response.data 类型: ", typeof response.data);
                console.log("response.data 值: ", response.data);
                
                // 确保生成的内容是字符串
                let contentToRender = '';
                
                if (typeof response.data === 'string') {
                    contentToRender = response.data;
                } else if (response.data && typeof response.data === 'object') {
                    // 如果是对象，尝试提取其中的文本内容
                    if (response.data.content) {
                        contentToRender = String(response.data.content);
                    } else if (response.data.text) {
                        contentToRender = String(response.data.text);
                    } else if (response.data.markdown) {
                        contentToRender = String(response.data.markdown);
                    } else {
                        // 如果没有常见的属性，尝试将整个对象转为 JSON 字符串
                        try {
                            contentToRender = JSON.stringify(response.data, null, 2);
                        } catch (e) {
                            contentToRender = 'Failed to parse content';
                        }
                    }
                } else if (response.data) {
                    // 其他非空值，尝试转为字符串
                    contentToRender = String(response.data);
                } else {
                    contentToRender = 'No content available';
                }
                
                console.log("处理后的内容: ", contentToRender);
                
                // 设置生成的内容
                setGeneratedContent(contentToRender);
                message.success('AI content generated successfully!');
                
                // 确保面板保持可见
                if (onKeepVisible) {
                    console.log('保持面板可见 - Keeping panel visible');
                    onKeepVisible();
                    
                    // 再次调用，确保在异步渲染后仍然可见
                    setTimeout(() => {
                        if (onKeepVisible) {
                            console.log('延迟保持面板可见 - Delayed keeping panel visible');
                            onKeepVisible();
                        }
                    }, 100);
                }
            } else {
                console.error('AI 内容生成失败 - Failed to generate AI content:', response?.message || 'Unknown error');
                message.error(response?.message || 'Failed to generate AI content');
            }
        } catch (error) {
            console.error('生成 AI 内容异常 - Exception generating AI content:', error);
            message.error('Failed to generate AI content');
        } finally {
            setGenerating(false);
        }
    };

    // Handle mode switch
    const handleModeSwitch = (checked: boolean) => {
        setIsPersonalMode(checked);
        setSelectedModel('');
        setGeneratedContent('');
        
        if (checked) {
            // 使用当前的 infoGuid 或从 currentInfoGuid 状态获取
            loadUserMindModels(infoGuid || currentInfoGuid);
        } else {
            loadSystemMindModels();
        }
    };

    // Initialize component
    useEffect(() => {
        console.log('组件初始化 - Component initializing, visible:', visible, 'status:', status);
        if (visible && status === 'success') {
            console.log('收藏成功，准备加载思维模型 - Collection success, preparing to load mind models');
            setCollectSuccess(true);
            
            // 设置infoGuid，优先使用传入的infoGuid，如果没有则从Storage中获取
            const setInfoGuidAndLoadModels = async () => {
                try {
                    let guidToUse = '';
                    
                    if (infoGuid) {
                        console.log('使用传入的infoGuid - Using passed infoGuid:', infoGuid);
                        setCurrentInfoGuid(infoGuid);
                        guidToUse = infoGuid; // 直接使用传入的值，而不是状态变量
                    } else {
                        // 尝试从chrome.storage中获取lastInfoGuid
                        console.log('尝试从Storage获取infoGuid - Trying to get infoGuid from storage');
                        const result = await chrome.storage.local.get('lastInfoGuid');
                        if (result.lastInfoGuid) {
                            console.log('从Storage获取infoGuid成功 - Successfully got infoGuid from storage:', result.lastInfoGuid);
                            setCurrentInfoGuid(result.lastInfoGuid);
                            guidToUse = result.lastInfoGuid; // 直接使用获取的值
                        } else {
                            console.warn('没有找到infoGuid - No infoGuid found in storage');
                        }
                    }
                    
                    // 加载思维模型
                    console.log('准备加载用户思维模型 - About to load user mind models with infoGuid:', guidToUse);
                    if (guidToUse) {
                        loadUserMindModels(guidToUse);
                    } else {
                        console.warn('没有可用的infoGuid，无法加载思维模型 - No available infoGuid, cannot load mind models');
                    }
                } catch (error) {
                    console.error('设置infoGuid时出错 - Error setting infoGuid:', error);
                }
            };
            
            setInfoGuidAndLoadModels();
        } else {
            console.log('组件条件不满足，不加载思维模型 - Component conditions not met, not loading mind models');
        }
    }, [visible, status, infoGuid]);

    // Load categories when component mounts or when status becomes success
    useEffect(() => {
        console.log('useEffect触发 - useEffect triggered:', { visible, status });
        if (visible && status === 'success') {
            console.log('✅ 条件满足，开始加载分类数据 - Conditions met, loading categories');
            loadCategories();
        } else {
            console.log('❌ 条件不满足 - Conditions not met:', { 
                visible, 
                status, 
                needsVisible: visible,
                needsSuccess: status === 'success'
            });
        }
    }, [visible, status]);

    // 添加一个测试用的useEffect，在组件首次渲染时就尝试加载分类
    useEffect(() => {
        console.log('🔍 测试useEffect - Test useEffect triggered, component props:', { visible, status, infoGuid });
        // 无论什么状态都尝试加载一次，用于测试API调用
        if (visible) {
            console.log('🧪 测试调用loadCategories - Test calling loadCategories');
            setTimeout(() => {
                loadCategories();
            }, 2000); // 延迟2秒调用，确保组件完全加载
        }
    }, [visible]); // 只依赖visible，确保在侧边栏打开时就调用

    // 过滤掉无效的模型项（value为null或text为空的项）
    const filterValidModels = (models: MindModel[]) => {
        if (!models || !Array.isArray(models)) return [];
        return models.filter(model => model && model.value && model.text);
    };
    
    const userValidModels = filterValidModels(userMindModels);
    const systemValidModels = filterValidModels(systemMindModels);
    const currentModels = isPersonalMode ? userValidModels : systemValidModels;
    
    // 添加日志追踪 currentModels
    useEffect(() => {
        console.log('原始模型数据 - Raw models data:', {
            userMindModels,
            systemMindModels
        });
        
        console.log('过滤后的模型数据 - Filtered models data:', {
            isPersonalMode,
            currentModelsLength: currentModels?.length || 0,
            userValidModelsLength: userValidModels?.length || 0,
            systemValidModelsLength: systemValidModels?.length || 0,
            currentModels
        });
    }, [currentModels, isPersonalMode, userMindModels, systemMindModels, userValidModels, systemValidModels]);

    if (!visible) return null;

    return (
        <div className="side-panel-overlay" style={{
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            backgroundColor: 'rgba(0, 0, 0, 0.3)',
            zIndex: 999998,
            display: 'flex',
            justifyContent: 'flex-end'
        }}>
            <div style={styles.sidePanel as React.CSSProperties}>
                <div style={styles.header as React.CSSProperties}>
                    <h2 style={styles.headerTitle as React.CSSProperties}>InfoKeyMind</h2>
                    <Button 
                        icon={<CloseOutlined />} 
                        onClick={onClose} 
                        style={styles.closeButton as React.CSSProperties}
                        type="text"
                    />
                </div>
                
                <div style={styles.content as React.CSSProperties}>
                    {status === 'loading' && (
                        <div style={styles.loadingContainer as React.CSSProperties}>
                            <Spin size="large" />
                            <Text style={styles.loadingText as React.CSSProperties}>
                                Saving in progress...
                            </Text>
                        </div>
                    )}
                    
                    {status === 'success' && (
                        <>
                            {/* Hide all elements above AI content when expanded */}
                            {!isExpanded && (
                                <>
                                    {/* Success Alert */}
                                    {showSuccessAlert && (
                                        <Alert
                                            message="Collection Successful"
                                            description="Page content has been successfully collected and processed."
                                            type="success"
                                            icon={<CheckCircleOutlined />}
                                            showIcon
                                            style={{ marginBottom: '16px' }}
                                        />
                                    )}
                                    
                                    {/* Expand button when category card is hidden */}
                                    {!showCategoryCard && (
                                        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: '16px' }}>
                                            <Button
                                                type="text"
                                                size="small"
                                                onClick={() => setShowCategoryCard(true)}
                                                style={{
                                                    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                                                    color: 'white',
                                                    border: 'none',
                                                    borderRadius: '8px',
                                                    padding: '4px 12px',
                                                    fontSize: '12px',
                                                    fontWeight: '500',
                                                    boxShadow: '0 2px 8px rgba(102, 126, 234, 0.3)',
                                                    transition: 'all 0.3s ease'
                                                }}
                                                onMouseEnter={(e) => {
                                                    e.currentTarget.style.transform = 'translateY(-1px)';
                                                    e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.4)';
                                                }}
                                                onMouseLeave={(e) => {
                                                    e.currentTarget.style.transform = 'translateY(0)';
                                                    e.currentTarget.style.boxShadow = '0 2px 8px rgba(102, 126, 234, 0.3)';
                                                }}
                                            >
                                                <span style={{ fontSize: '10px', marginRight: '4px' }}>📂</span>
                                                Show Categories
                                            </Button>
                                        </div>
                                    )}
                                    
                                    {/* Category Selection */}
                                    {showCategoryCard && (
                            <Card 
                                size="small" 
                                style={{ 
                                    marginBottom: '16px',
                                    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                                    border: 'none',
                                    borderRadius: '12px',
                                    boxShadow: '0 4px 15px rgba(102, 126, 234, 0.2)'
                                }}
                            >
                                <div style={{ color: 'white' }}>
                                    <div style={{ 
                                        display: 'flex', 
                                        alignItems: 'center', 
                                        justifyContent: 'space-between',
                                        marginBottom: '12px',
                                        fontSize: '14px',
                                        fontWeight: '600'
                                    }}>
                                        <div style={{ display: 'flex', alignItems: 'center' }}>
                                            <span style={{ marginRight: '8px' }}>📂</span>
                                            <Text strong style={{ color: 'white' }}>Page Category</Text>
                                            {loadingCategories && (
                                                <Spin size="small" style={{ marginLeft: '8px' }} />
                                            )}
                                        </div>
                                        <Button
                                            type="text"
                                            size="small"
                                            onClick={() => setShowCategoryCard(false)}
                                            style={{
                                                color: 'white',
                                                border: 'none',
                                                padding: '2px 6px',
                                                fontSize: '12px',
                                                lineHeight: '1',
                                                minWidth: 'auto',
                                                height: 'auto'
                                            }}
                                            title="Hide category card"
                                        >
                                            ×
                                        </Button>
                                    </div>
                                    
                                    <Space direction="vertical" style={{ width: '100%' }} size="small">
                                        {/* Custom Searchable Dropdown */}
                                        <div style={{ position: 'relative', width: '100%' }}>
                                            {/* Search Input / Display */}
                                            <input
                                                type="text"
                                                placeholder={
                                                    loadingCategories 
                                                        ? "加载分类中... - Loading categories..."
                                                        : selectedCategory 
                                                            ? selectedCategoryLabel 
                                                            : "搜索并选择分类 - Search and select category"
                                                }
                                                value={isDropdownOpen ? searchTerm : (selectedCategory ? selectedCategoryLabel : '')}
                                                onChange={(e) => {
                                                    setSearchTerm(e.target.value);
                                                    if (!isDropdownOpen) setIsDropdownOpen(true);
                                                }}
                                                onFocus={() => {
                                                    if (!loadingCategories) {
                                                        setIsDropdownOpen(true);
                                                        setSearchTerm('');
                                                    }
                                                }}
                                                onBlur={() => {
                                                    // Delay closing to allow for option selection
                                                    setTimeout(() => setIsDropdownOpen(false), 200);
                                                }}
                                                disabled={loadingCategories}
                                                style={{
                                                    width: '100%',
                                                    padding: '8px 12px',
                                                    fontSize: '14px',
                                                    borderRadius: '8px',
                                                    border: '1px solid rgba(255, 255, 255, 0.3)',
                                                    backgroundColor: loadingCategories ? 'rgba(255, 255, 255, 0.5)' : 'rgba(255, 255, 255, 0.9)',
                                                    color: loadingCategories ? '#999' : '#000000d9',
                                                    outline: 'none',
                                                    cursor: loadingCategories ? 'not-allowed' : 'text'
                                                }}
                                            />
                                            
                                            {/* Dropdown Arrow */}
                                            <div
                                                onClick={() => {
                                                    setIsDropdownOpen(!isDropdownOpen);
                                                    setSearchTerm('');
                                                }}
                                                style={{
                                                    position: 'absolute',
                                                    right: '8px',
                                                    top: '50%',
                                                    transform: 'translateY(-50%)',
                                                    cursor: 'pointer',
                                                    fontSize: '12px',
                                                    color: '#666',
                                                    userSelect: 'none'
                                                }}
                                            >
                                                {isDropdownOpen ? '▲' : '▼'}
                                            </div>
                                            
                                            {/* Dropdown Options */}
                                            {isDropdownOpen && (
                                                <div style={{
                                                    position: 'absolute',
                                                    top: '100%',
                                                    left: 0,
                                                    right: 0,
                                                    backgroundColor: 'white',
                                                    border: '1px solid rgba(255, 255, 255, 0.3)',
                                                    borderRadius: '8px',
                                                    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                                                    zIndex: 1000,
                                                    maxHeight: '200px',
                                                    overflowY: 'auto'
                                                }}>
                                                    {filteredCategories.length > 0 ? (
                                                        filteredCategories.map((category, index) => (
                                                            <div
                                                                key={`filtered-category-${index}`}
                                                                onClick={() => {
                                                                    console.log('选择了分类 - Selected category:', category.value);
                                                                    setSelectedCategory(category.value);
                                                                    setIsDropdownOpen(false);
                                                                    setSearchTerm('');
                                                                }}
                                                                style={{
                                                                    padding: '8px 12px',
                                                                    cursor: 'pointer',
                                                                    borderBottom: index < filteredCategories.length - 1 ? '1px solid #f0f0f0' : 'none',
                                                                    fontSize: '14px',
                                                                    color: '#000000d9',
                                                                    backgroundColor: selectedCategory === category.value ? '#f6f6f6' : 'white',
                                                                    transition: 'background-color 0.2s ease'
                                                                }}
                                                                onMouseEnter={(e) => {
                                                                    e.currentTarget.style.backgroundColor = '#e6f7ff';
                                                                }}
                                                                onMouseLeave={(e) => {
                                                                    e.currentTarget.style.backgroundColor = selectedCategory === category.value ? '#f6f6f6' : 'white';
                                                                }}
                                                            >
                                                                {category.label}
                                                            </div>
                                                        ))
                                                    ) : (
                                                        <div style={{
                                                            padding: '8px 12px',
                                                            fontSize: '14px',
                                                            color: '#999',
                                                            textAlign: 'center'
                                                        }}>
                                                            没有找到匹配的分类 - No matching categories
                                                        </div>
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                        
                                        <Button
                                            type="primary"
                                            onClick={handleCategoryAssociation}
                                            loading={associatingCategory}
                                            disabled={!selectedCategory}
                                            block
                                            style={{
                                                background: 'rgba(255, 255, 255, 0.2)',
                                                borderColor: 'rgba(255, 255, 255, 0.3)',
                                                color: 'white',
                                                fontWeight: '600',
                                                height: '36px',
                                                borderRadius: '8px',
                                                backdropFilter: 'blur(10px)',
                                                transition: 'all 0.3s ease'
                                            }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.background = 'rgba(255, 255, 255, 0.3)';
                                                e.currentTarget.style.transform = 'translateY(-1px)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.background = 'rgba(255, 255, 255, 0.2)';
                                                e.currentTarget.style.transform = 'translateY(0)';
                                            }}
                                        >
                                            {associatingCategory ? 'Associating...' : 'Associate with Category'}
                                        </Button>
                                    </Space>
                                </div>
                            </Card>
                                    )}
                                    
                                    {/* Mode Switch */}
                                    <Card size="small" style={{ marginBottom: '16px' }}>
                                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                            <Space align="center">
                                                <UserOutlined style={{ color: isPersonalMode ? '#1677ff' : '#999' }} />
                                                <Text strong>Personal Models</Text>
                                                <Switch 
                                                    checked={isPersonalMode}
                                                    onChange={handleModeSwitch}
                                                />
                                                <Text strong>System Models</Text>
                                                <RobotOutlined style={{ color: !isPersonalMode ? '#1677ff' : '#999' }} />
                                            </Space>
                                        </div>
                                    </Card>
                                    
                                    {/* Model Selection */}
                                    <Card size="small" style={{ marginBottom: '16px' }}>
                                        <Space direction="vertical" style={{ width: '100%' }}>
                                            <Text strong>
                                                {isPersonalMode ? 'Your Mind Models' : 'System Mind Models'}
                                            </Text>
                                            
                                            {/* 使用原生下拉菜单替代 Ant Design Select */}
                                            <div style={{ marginBottom: '16px' }}>
                                                <select 
                                                    style={{ 
                                                        width: '100%', 
                                                        padding: '8px', 
                                                        fontSize: '16px',
                                                        borderRadius: '6px',
                                                        borderColor: '#d9d9d9',
                                                        color: '#000000d9'
                                                    }}
                                                    value={selectedModel}
                                                    onChange={(e) => {
                                                        console.log('选择了模型 - Selected model:', e.target.value);
                                                        setSelectedModel(e.target.value);
                                                    }}
                                                    disabled={!currentModels || currentModels.length === 0}
                                                >
                                                    <option value="">选择模型 - Select a mind model</option>
                                                    {currentModels && currentModels.map((model, index) => (
                                                        <option 
                                                            key={`native-${index}`} 
                                                            value={model.value || ''}
                                                            disabled={!model.value}
                                                        >
                                                            {model.text || 'No name'}
                                                        </option>
                                                    ))}
                                                </select>
                                            </div>
                                            
                                            <Button
                                                type="primary"
                                                icon={<ThunderboltOutlined />}
                                                onClick={generateAIContent}
                                                loading={generating}
                                                disabled={!selectedModel}
                                                size="large"
                                                block
                                                style={{ marginTop: '8px' }}
                                            >
                                                {generating ? 'Generating...' : 'Generate Analysis'}
                                            </Button>
                                        </Space>
                                    </Card>
                                </>
                            )}
                            
                            {/* Generated Content */}
                            {generatedContent && (
                                <Card 
                                    title={
                                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                             <span>🤖 AI Analysis Result</span>
                                             <div>
                                                 <Button
                                                     type="text"
                                                     size="small"
                                                     onClick={() => setIsExpanded(!isExpanded)}
                                                     title={isExpanded ? 'Compress' : 'Expand'}
                                                     style={{ marginRight: '4px' }}
                                                 >
                                                     {isExpanded ? '📉' : '📈'}
                                                 </Button>
                                                 <Button
                                                     type="text"
                                                     size="small"
                                                     icon={<FullscreenOutlined />}
                                                     onClick={() => setShowFullscreen(true)}
                                                     title="全屏查看"
                                                 />
                                             </div>
                                         </div>
                                    }
                                    size="small" 
                                    style={{ marginBottom: '16px' }}
                                >
                                    <div
                                        className="markdown-content"
                                        style={{
                                            maxHeight: isExpanded ? '600px' : '300px',
                                            overflowY: 'auto',
                                            transition: 'max-height 0.3s ease'
                                        }}
                                    >
                                        {(() => {
                                            console.log('Sidebar generatedContent:', generatedContent);
                                            console.log('generatedContent type:', typeof generatedContent);
                                            console.log('generatedContent length:', generatedContent?.length);
                                            
                                            if (typeof generatedContent === 'string' && generatedContent.trim()) {
                                                return parseMarkdownToJSX(generatedContent);
                                            } else {
                                                return (
                                                    <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                                                        内容正在准备中...
                                                    </div>
                                                );
                                            }
                                        })()}
                                    </div>
                                </Card>
                            )}

                            {/* 自定义全屏覆盖层 */}
                            {showFullscreen && (
                                <div
                                    style={{
                                        position: 'fixed',
                                        top: 0,
                                        left: 0,
                                        right: 0,
                                        bottom: 0,
                                        backgroundColor: 'rgba(0, 0, 0, 0.6)',
                                        zIndex: 999999,
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        padding: '20px'
                                    }}
                                    onClick={(e) => {
                                        // 点击遮罩关闭
                                        if (e.target === e.currentTarget) {
                                            setShowFullscreen(false);
                                        }
                                    }}
                                >
                                    <div
                                        style={{
                                            backgroundColor: 'white',
                                            borderRadius: '8px',
                                            width: '90%',
                                            maxWidth: '1200px',
                                            maxHeight: '80vh',
                                            display: 'flex',
                                            flexDirection: 'column',
                                            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.15)'
                                        }}
                                        onClick={(e) => e.stopPropagation()}
                                    >
                                        {/* 标题栏 */}
                                        <div
                                            style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'space-between',
                                                padding: '16px 20px',
                                                borderBottom: '1px solid #f0f0f0',
                                                backgroundColor: '#fafafa'
                                            }}
                                        >
                                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                                <RobotOutlined style={{ marginRight: '8px', color: '#1677ff', fontSize: '16px' }} />
                                                <span style={{ fontSize: '16px', fontWeight: 500 }}>AI Analysis Result</span>
                                            </div>
                                            <Button
                                                type="text"
                                                icon={<CloseOutlined />}
                                                onClick={() => setShowFullscreen(false)}
                                                style={{ border: 'none' }}
                                            />
                                        </div>
                                        
                                        {/* 内容区域 */}
                                        <div
                                            style={{
                                                flex: 1,
                                                overflow: 'auto',
                                                padding: '20px'
                                            }}
                                        >
                                            <div
                                                className="markdown-content"
                                                style={{
                                                    fontSize: '14px',
                                                    lineHeight: '1.6',
                                                    color: '#333'
                                                }}
                                            >
                                                {typeof generatedContent === 'string' && generatedContent.trim() ? (
                                                    parseMarkdownToJSX(generatedContent)
                                                ) : (
                                                    <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
                                                        内容正在准备中...
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                        
                                        {/* 底部按钮 */}
                                        <div
                                            style={{
                                                padding: '16px 20px',
                                                borderTop: '1px solid #f0f0f0',
                                                textAlign: 'right',
                                                backgroundColor: '#fafafa'
                                            }}
                                        >
                                            <Button
                                                type="primary"
                                                onClick={() => setShowFullscreen(false)}
                                            >
                                                关闭
                                            </Button>
                                        </div>
                                    </div>
                                </div>
                            )}
                            
                            {/* Loading State */}
                            {generating && (
                                <div style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    padding: '20px'
                                }}>
                                    <Spin size="large" />
                                    <Text style={{ marginTop: '16px', color: '#1677ff' }}>
                                        AI is analyzing your content...
                                    </Text>
                                </div>
                            )}
                            
                            {/* Knowledge Base Button */}
                            <div style={{ textAlign: 'center', marginTop: '16px' }}>
                                <Button
                                    icon={<ReadOutlined />}
                                    onClick={() => {
                                        window.open(KNOWLEDGE_LIB_ROUTER)
                                    }}
                                >
                                    Open the knowledge base
                                </Button>
                            </div>
                        </>
                    )}
                    
                    {status === 'error' && (
                        <Card>
                            <div style={{ textAlign: 'center', padding: '20px 0' }}>
                                <WarningOutlined style={styles.errorIcon as React.CSSProperties} />
                                <Title level={3} style={{ color: '#ff4d4f' }}>
                                    Collection Failed!
                                </Title>
                                {errorMessage && (
                                    <Text type="secondary" style={{ display: 'block', marginBottom: '20px' }}>
                                        {errorMessage}
                                    </Text>
                                )}
                                <Divider />
                                <Space>
                                    <Button
                                        type="primary"
                                        danger
                                        onClick={() => {
                                            // Trigger collection again
                                            const event = new CustomEvent('retry-collection');
                                            document.dispatchEvent(event);
                                        }}
                                    >
                                        Try Again
                                    </Button>
                                    <Button
                                        onClick={() => {
                                            window.open(KNOWLEDGE_LIB_ROUTER)
                                        }}
                                    >
                                        Open knowledge base
                                    </Button>
                                </Space>
                            </div>
                        </Card>
                    )}
                </div>
            </div>
        </div>
    );
};

/**
 * 收藏文章
 */
export namespace GetUrlPanel {
    export const id = 'GET_URL';
    
    // Panel state management
    let panelContainer: HTMLDivElement | null = null;
    let panelRoot: any = null;
    
    /**
     * 消费消息
     * @param message 
     * @returns 
     */
    export const consume = (message: Message) => {
        console.log('GetUrlPanel.consume called with message:', message);
        if (message.action === 'GetUrl') {
            // Get page content from body
            const content = document.body.innerText;
            return {
                url: window.location.href,
                title: window.document.title,
                content: content
            }
        }

        if (message.action === 'GetUrlStart') {
            showPanel('loading');
            return {
                message: 'success'
            }
        }

        if (message.action === 'GetUrlResolve') {            
            console.log('收到GetUrlResolve消息，带有infoGuid - Received GetUrlResolve message with infoGuid:', message.data?.infoGuid);
            showPanel('success', undefined, message.data?.infoGuid);
            return {
                message: 'success'
            }
        }

        if (message.action === 'GetUrlReject') {
            showPanel('error', message.data?.message);
            return {
                message: 'error',
                error: message.data?.message || 'Collection failed'
            }
        }
        
        if (message.action === 'ClosePanel') {
            closePanel();
            return {
                message: 'success'
            }
        }
    }
    
    /**
     * Show the side panel with specified status
     * @param status - Panel status ('loading', 'success', 'error')
     * @param errorMessage - Optional error message to display
     * @param infoGuid - Optional infoGuid for loading mind models
     */
    const showPanel = (status: 'loading' | 'success' | 'error', errorMessage?: string, infoGuid?: string) => {
        // Create container if it doesn't exist
        if (!panelContainer) {
            panelContainer = document.createElement('div');
            panelContainer.id = 'ikm-panel-container';
            document.body.appendChild(panelContainer);
        }
        
        // Render the panel
        try {
            const ReactDOM = require('react-dom');
            if (!ReactDOM) {
                console.error('ReactDOM is not available');
                return;
            }
            
            // For React 18+
            if (ReactDOM.createRoot) {
                if (!panelRoot) {
                    panelRoot = ReactDOM.createRoot(panelContainer);
                }
                panelRoot.render(
                    <GetUrlPanelComponent 
                        visible={true} 
                        status={status} 
                        errorMessage={errorMessage}
                        onClose={closePanel}
                        infoGuid={infoGuid} // 传递infoGuid给组件
                        onKeepVisible={() => {
                            console.log('保持面板可见 - Keeping panel visible from callback');
                            // 这里不需要做任何事情，只需要提供回调函数
                            // 防止面板自动关闭
                        }}
                    />
                );
            } 
            // For React 17 and below
            else {
                ReactDOM.render(
                    <GetUrlPanelComponent 
                        visible={true} 
                        status={status} 
                        errorMessage={errorMessage}
                        onClose={closePanel}
                        infoGuid={infoGuid} // 传递infoGuid给组件
                        onKeepVisible={() => {
                            console.log('保持面板可见 - Keeping panel visible from callback');
                            // 这里不需要做任何事情，只需要提供回调函数
                            // 防止面板自动关闭
                        }}
                    />,
                    panelContainer
                );
            }
        } catch (error) {
            console.error('Failed to render GetUrlPanel:', error);
        }
    };
    
    /**
     * Close the side panel
     */
    const closePanel = () => {
        if (panelContainer) {
            try {
                const ReactDOM = require('react-dom');
                
                // For React 18+
                if (panelRoot) {
                    panelRoot.render(
                        <GetUrlPanelComponent 
                            visible={false} 
                            status="success" 
                            onClose={() => {}} 
                        />
                    );
                } 
                // For React 17 and below
                else if (ReactDOM.unmountComponentAtNode) {
                    ReactDOM.unmountComponentAtNode(panelContainer);
                }
                
                // Remove container after animation
                setTimeout(() => {
                    if (panelContainer && panelContainer.parentNode) {
                        panelContainer.parentNode.removeChild(panelContainer);
                        panelContainer = null;
                        panelRoot = null; // 重置panelRoot，确保下次可以重新创建
                        console.log('GetUrlPanel: Panel container and root have been reset');
                    }
                }, 300);
            } catch (error) {
                console.error('Failed to close GetUrlPanel:', error);
            }
        }
    };

    export const createGetUrlAction = () => ({
        id,
        action: GetUrlPanel.Action.GetUrl
    })

    export const createGetUrlStartAction = () => ({
        id,
        action: GetUrlPanel.Action.GetUrlStart,
    })

    export const createGetUrlResolveAction = (infoGuid?: string) => ({
        id,
        action: GetUrlPanel.Action.GetUrlResolve,
        data: { infoGuid }
    })

    export const createGetUrlRejectAction = (errorMessage?: string) => ({
        id,
        action: GetUrlPanel.Action.GetUrlReject,
        data: errorMessage ? { message: errorMessage } : undefined
    })
    
    export const createClosePanelAction = () => ({
        id,
        action: GetUrlPanel.Action.ClosePanel,
    })
}